﻿///
/// Authors: Lee Gary 
///
/// Date: 24/09/2010
///
/// Purpose: 
///
/// Base form for ease of using log4net logging capabilities
/// 
/// Future:
/// 1.) To cater for true logging capabilities based on log levels (Info, debug, error, etc)
/// 
using System;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using log4net;

namespace WinApp.Common
{
    public partial class BaseForm : Form
    {
        protected BaseForm()
        {
            if (log4net.LogManager.GetRepository().Configured == false)
            {
                log4net.Config.XmlConfigurator.Configure();
            }
        }
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static StringBuilder sb;
        private static string NEWLINE = System.Environment.NewLine;
        private static string loggerName;

        /// <summary>
        /// Enum for loglevel
        /// </summary>
        protected enum LogLevel
        {
            Info,
            Debug,
            Error
        };

        /// <summary>
        /// Easy way to implement different log levels, removed stringbuilder instance due
        /// to change of logging requirements to exclude timelogs, log levels and thread
        /// </summary>
        /// <param name="loglevel"></param>
        /// <param name="msg"></param>
        protected static void WriteLog(LogLevel loglevel, string msg)
        {
            #region switch loglevel
            switch (loglevel)
            {
                case LogLevel.Debug:
                    {
                        log.Debug(msg);
                        break;
                    }
                case LogLevel.Error:
                    {
                        log.Error(msg);
                        break;
                    }
                case LogLevel.Info:
                    {
                        log.Info(msg);
                        break;
                    }
            }
            #endregion
        }

        /// <summary>
        /// Dreaded exception log which hopefully i do not have to use
        /// </summary>
        /// <param name="ex"></param>
        protected static void ExceptionLog(Exception ex)
        {
            loggerName = MethodBase.GetCurrentMethod().DeclaringType.ToString();
            ILog logEngine = LogManager.GetLogger(loggerName);
            sb = new StringBuilder();

            if (logEngine.IsFatalEnabled && !ex.Message.Contains("Thread was being aborted"))
            {
                sb.Append(NEWLINE);
                sb.Append(ex.Message);
                sb.Append(NEWLINE);
                sb.Append(ex.StackTrace);
                sb.Append(NEWLINE);
                logEngine.Error(sb.ToString());
            }
        }

    }
}
